package com.vcredit.creditcat.framework.util;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@SuppressWarnings("deprecation")
public class HttpClientUtil {
	/***
	 * 通过JSON方式提交
	 * 
	 * @param url
	 * @param obj
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings("resource")
	public static String doPostByJson(String url, Object obj) throws IOException {
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpPost method = new HttpPost(url);
		method.addHeader("Content-type", "application/json; charset=utf-8");
		method.setHeader("Accept", "application/json");
		method.setEntity(new StringEntity(JacksonUtil.Obj2Json(obj), Charset.forName("UTF-8")));
		HttpResponse response = httpClient.execute(method);

		int statusCode = response.getStatusLine().getStatusCode();
		if (statusCode != HttpStatus.SC_OK) {

		}

		return EntityUtils.toString(response.getEntity(), "UTF-8");
	}

	/***
	 * 通过JSON方式提交
	 * 
	 * @param url
	 * @param obj
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings({ "rawtypes", "resource" })
	public static String doPostByJson(String url, Map map) throws IOException {
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpPost method = new HttpPost(url);

		method.addHeader("Content-type", "application/json; charset=utf-8");
		method.setHeader("Accept", "application/json");
		method.setEntity(new StringEntity(JacksonUtil.Obj2Json(map), Charset.forName("UTF-8")));
		HttpResponse response = httpClient.execute(method);

		int statusCode = response.getStatusLine().getStatusCode();
		if (statusCode != HttpStatus.SC_OK) {

		}

		return EntityUtils.toString(response.getEntity(), "UTF-8");
	}

	/***
	 * 
	 * @param url
	 * @param obj
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings("resource")
	public static String doPostByJson(String url, String obj) throws IOException {
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpPost method = new HttpPost(url);

		method.addHeader("Content-type", "application/json; charset=utf-8");
		method.setHeader("Accept", "application/json");
		method.setEntity(new StringEntity(JacksonUtil.Obj2Json(obj), Charset.forName("UTF-8")));
		HttpResponse response = httpClient.execute(method);

		int statusCode = response.getStatusLine().getStatusCode();
		if (statusCode != HttpStatus.SC_OK) {

		}

		return EntityUtils.toString(response.getEntity(), "UTF-8");
	}

	public static String doPostFile(String sourceUrl, String targetUrl) throws Exception {
		File file = new File(sourceUrl);
		URL url = new URL(targetUrl);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setDoInput(true);
		connection.setDoOutput(true);
		connection.setRequestMethod("POST");
		connection.addRequestProperty("FileName", file.getName());
		connection.setRequestProperty("content-type", "application/json");
		BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream());

		// 读取文件上传到服务器
		FileInputStream fileInputStream = new FileInputStream(file);
		byte[] bytes = new byte[1024];
		int numReadByte = 0;
		while ((numReadByte = fileInputStream.read(bytes, 0, 1024)) > 0) {
			out.write(bytes, 0, numReadByte);
		}

		out.flush();
		fileInputStream.close();

		String res = "";
		StringBuffer strBuf = new StringBuffer();
		BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
		String line = null;
		while ((line = reader.readLine()) != null) {
			strBuf.append(line).append("\n");
		}
		res = strBuf.toString();
		reader.close();
		reader = null;
		return res;
	}

	/**
	 * 创建 SSL连接
	 * 
	 * @return
	 * @throws GeneralSecurityException
	 */
	@SuppressWarnings("unused")
	private static CloseableHttpClient createSSLInsecureClient() throws GeneralSecurityException {
		try {
			SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
				@Override
				public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					return true;
				}
			}).build();

			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {

				@Override
				public boolean verify(String arg0, SSLSession arg1) {
					return true;
				}

				@Override
				public void verify(String host, SSLSocket ssl) throws IOException {
				}

				@Override
				public void verify(String host, X509Certificate cert) throws SSLException {
				}

				@Override
				public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
				}

			});

			return HttpClients.custom().setSSLSocketFactory(sslsf).build();

		} catch (GeneralSecurityException e) {
			throw e;
		}
	}
	
	@SuppressWarnings({ "unchecked" })
	public static Map<String, Object> json2Map(String json) {
		Map<String, Object> result = null;
		ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
		try {
			result = mapper.readValue(json, Map.class);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

}	
